package org.qydjk.console.controller.article;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.Article;
import org.qydjk.common.pojo.ArticleCatagory;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.util.ThumbnailatorUtils;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.common.vo.Tree;
import org.qydjk.common.vo.autocomplete.AutoCompleteBean;
import org.qydjk.common.vo.autocomplete.AutoCompleteResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lanan on 2017/12/20 0020.
 */

@Controller
@RequestMapping("/article")
public class ArticleController extends BaseController {
    /**
     * 文章页面
     * @return 文章地址
     */
    @RequestMapping("/index.do")
    public String articleIndex() {
        return "/article/article";
    }



    /******************************  文章分类  *******************************/
    /**
     * 文章分类列表
     * @return 返回查询结果
     */
    @RequestMapping("/category/list.do")
    @ResponseBody
    public Object articleCategoryList() {
        List<ArticleCatagory> articleCatagories = new ArrayList<ArticleCatagory>();
        String sql = "SELECT * FROM qy_article_catagory WHERE 1 = 1";
        sql += " ORDER BY ord desc";
        try {
            articleCatagories = baseService.findBySQL(sql, ArticleCatagory.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return articleCatagories;
    }

    /**
     * 添加文章分类
     * @param articleCatagory 传入的数据
     * @return
     */
    @RequestMapping("/category/insert.do")
    @ResponseBody
    public Object articleCategoryInsert(ArticleCatagory articleCatagory) {
        articleCatagory.setStatus(0);
        if (articleCatagory.getOrd() == null) articleCatagory.setOrd(0);
        return handleSaveOrUpdate(true, articleCatagory);
    }

    /**
     * 更新文章分类
     * @param articleCatagory 传入的数据
     * @return
     */
    @RequestMapping("/category/update.do")
    @ResponseBody
    public Object articleCategoryUpdate(ArticleCatagory articleCatagory) {
        return handleSaveOrUpdate(false, articleCatagory);
    }

    /**
     * 删除文章分类
     * @param id) 要删除的内容id
     * @return 处理结果
     */
    @RequestMapping("/category/delete.do")
    @ResponseBody
    public Object articleCategoryDelete(Integer id) {
        JSONObject resp = new JSONObject();
        Integer count = 0;
        String msg = "";
        ArticleCatagory articleCatagory = null;
        try {
            articleCatagory = baseService.get(ArticleCatagory.class, id.intValue());
            Integer level = articleCatagory.getLevel();
            if (level == 1) {
                String sql = "SELECT COUNT(id) FROM qy_article_catagory WHERE parent_id = '"+ id +"' AND `level` = '2'";
                count = baseService.getRecordCountSQL(sql);
                msg = "分类\"" + articleCatagory.getName() + "\"含有子分类！删除失败!";
                if (count <= 0) {
                    String articleSql = "SELECT COUNT(id) FROM qy_article WHERE catagory_one_id = '" + id + "'";
                    count = baseService.getRecordCountSQL(articleSql);
                    msg = "分类\"" + articleCatagory.getName() + "\"含有文章！删除失败!";
                }
            } else if (level == 2) {
                String articleSql = "SELECT COUNT(id) FROM qy_article WHERE catagory_two_id = '" + id + "'";
                count = baseService.getRecordCountSQL(articleSql);
                msg = "分类\"" + articleCatagory.getName() + "\"含有文章！删除失败!";
            }
        } catch (Exception e) {
            resp.put("success", false);
            resp.put("msg", e.toString());
            return JSON.toJSON(resp);
        }
        if (count > 0) {
            resp.put("success", false);
            resp.put("msg", msg);
            return JSON.toJSON(resp);
        }
        return handelDelete(articleCatagory, resp);
    }

    /**
     * 公共处理添加和修改部分
     * @param isSave true:添加 false:修改
     * @param articleCatagory 传入的对象
     * @return 处理结果
     */
    private Object handleSaveOrUpdate(Boolean isSave, ArticleCatagory articleCatagory) {
        Integer parentId = articleCatagory.getParentId();
        articleCatagory.setUpdateTime(new Date());
        // 如果是添加
        if (isSave) {
            // 如果父类id不存在 则是一级分类 否则是二级分类
            if (parentId == null) articleCatagory.setLevel(1);
            else articleCatagory.setLevel(2);
            articleCatagory.setCreateTime(new Date());
            return handleSave(articleCatagory);
        }
        return categaryUpdateHandel(articleCatagory);
    }

    /**
     * 更新处理
     * @param articleCatagory 预处理数据
     * @return 处理结果
     */
    private Object categaryUpdateHandel(ArticleCatagory articleCatagory) {
        Integer id = articleCatagory.getId();
        Integer parentId = articleCatagory.getParentId();
        ArticleCatagory uda = null;
        String msg = "";
        Integer count = 0;
        try {
            uda = baseService.get(ArticleCatagory.class, id.intValue());
            Integer level = uda.getLevel();
            if (level == 1 && parentId != null) {
                if (uda.getId() == parentId) {
                    count = 1;
                    msg = "分类\"" + uda.getName() + "\"不能设置自己为上级分类！修改失败！";
                } else {
                    String sql = "SELECT COUNT(id) FROM qy_article_catagory WHERE parent_id = '"+ id +"' AND `level` = '2'";
                    count = baseService.getRecordCountSQL(sql);
                    msg = "分类\"" + uda.getName() + "\"下还有子分类，不可设置上级分类！修改失败！";
                }
                if (count > 0) {
                    JSONObject resp = new JSONObject();
                    resp.put("success", false);
                    resp.put("msg", msg);
                    return JSON.toJSON(resp);
                }
            }
            if (parentId != null) {
                articleCatagory.setLevel(2);
                ArticleCatagory parentArticleCatagory = baseService.get(ArticleCatagory.class, parentId);
                if (parentArticleCatagory.getStatus() == 0) {
                    articleCatagory.setStatus(0);
                }
            } else {
                articleCatagory.setLevel(1);
            }
            // 如果父类id改变且等于null 该项成为一级分类 将启用关闭
            if (parentId != uda.getParentId() && parentId == null) {
                articleCatagory.setStatus(0);
            }
        } catch (Exception e) {
            JSONObject resp = new JSONObject();
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.toString());
            return JSON.toJSON(resp);
        }
        if (parentId == null) {
            uda.setParentId(null);
        }

        try {
            // 处理当分类父类变动时该类下文章的处理
            String updateArticleSql = null;
            if (articleCatagory.getLevel() == 1 && uda.getLevel() == 2) {
                updateArticleSql = "UPDATE qy_article SET catagory_one = '" + articleCatagory.getName() + "', " +
                        "catagory_one_id = '" + articleCatagory.getId() + "', " +
                        "catagory_two = '', catagory_two_id = " + articleCatagory.getParentId() + " " +
                        " WHERE catagory_two_id = '" + articleCatagory.getId() + "'";
            } else if (articleCatagory.getLevel() == 2 && uda.getLevel() == 1) {
                ArticleCatagory parentArticleCatagory = baseService.get(ArticleCatagory.class, articleCatagory.getParentId());
                updateArticleSql = "UPDATE qy_article SET catagory_one = '" + parentArticleCatagory.getName() + "', " +
                        "catagory_one_id = '" + parentArticleCatagory.getId() + "', " +
                        "catagory_two = '" + articleCatagory.getName() + "', catagory_two_id = '" + articleCatagory.getId() + "'" +
                        " WHERE catagory_one_id = '" + articleCatagory.getId() + "'";
            } else if (articleCatagory.getLevel() == 2 && uda.getLevel() == 2 && articleCatagory.getParentId() != uda.getParentId()) {
                ArticleCatagory parentArticleCatagory = baseService.get(ArticleCatagory.class, articleCatagory.getParentId());
                updateArticleSql = "UPDATE qy_article SET catagory_one = '" + parentArticleCatagory.getName() + "', " +
                        "catagory_one_id = '" + parentArticleCatagory.getId() + "', " +
                        "catagory_two = '" + articleCatagory.getName() + "', catagory_two_id = '" + articleCatagory.getId() + "'" +
                        " WHERE catagory_two_id = '" + articleCatagory.getId() + "'";
            }
            if (!StringUtil.isEmptyOrNull(updateArticleSql)) {
                baseService.excuteSQL(updateArticleSql);
            }
        } catch (Exception e) {
            JSONObject resp = new JSONObject();
            resp.put("success", false);
            resp.put("msg", "修改失败");
            return JSON.toJSON(resp);
        }
        return handleUpdate(articleCatagory, uda);
    }

    /**
     * 启用和禁用处理 文章分类
     * @param id 操作项id
     * @param status 操作成的状态
     * @return 处理结果
     */
    @RequestMapping("/category/changeCategoryStatusToEnableOrDisable.do")
    @ResponseBody
    public Object changeCategoryStatusToEnableOrDisable(Integer id, Integer status) {
        JSONObject resp = new JSONObject();
        try {
            ArticleCatagory articleCatagory = baseService.get(ArticleCatagory.class, id);
            Date date = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = sf.format(date);
            if (articleCatagory.getLevel() == 1 && status == 0) {
                String sql = "UPDATE qy_article_catagory SET `status` = '0', update_time = '" + dateStr + "' WHERE `status` = '1' AND parent_id = '" + id + "'";
                baseService.excuteSQL(sql);

                String sqlArticle = "UPDATE qy_article SET `status` = '0', update_time = '" + dateStr + "' WHERE `status` = '1' AND catagory_one_id = '" + id + "'";
                baseService.excuteSQL(sqlArticle);
            }
            if (articleCatagory.getLevel() == 2) {
                if (status == 1) {
                    ArticleCatagory parentArticleCatagory = baseService.get(ArticleCatagory.class, articleCatagory.getParentId());
                    if (parentArticleCatagory.getStatus() == 0) {
                        resp.put("success", false);
                        resp.put("msg", "必须启用该类上级分类，操作失败！");
                        return JSON.toJSON(resp);
                    }
                } else {
                    String sqlArticle = "UPDATE qy_article SET `status` = '0', update_time = '" + dateStr + "'  WHERE `status` = '1' AND catagory_two_id = '" + id + "'";
                    baseService.excuteSQL(sqlArticle);
                }
            }
            articleCatagory.setStatus(status);
            articleCatagory.setUpdateTime(new Date());
            baseService.saveOrUpdate(articleCatagory);
            resp.put("success", true);
            return JSON.toJSON(resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }



    /******************************  文章  *******************************/
    /**
     * 文章列表
     * @param page 当前页
     * @param rows 总页数
     * @return 结果
     */
    @RequestMapping("/list.do")
    @ResponseBody
    public Object articleList(int page, int rows) {
        List<Article> articles = new ArrayList<Article>();
        Integer total = 0;
        String sql = "SELECT * FROM qy_article WHERE 1 = 1";
        String countSql = "SELECT COUNT(id) FROM qy_article WHERE 1 = 1";

        sql += addArticleWhereStr();
        countSql += addArticleWhereStr();

        sql += " ORDER BY ord desc";
        try {
            articles = baseService.findBySQL(sql, Article.class, new HibernatePage(page, rows));
            total = baseService.getRecordCountSQL(countSql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new EasyUIResponse(total, articles);
    }

    /**
     * 添加点击文章分类时查询文章的条件
     * @return 条件语句
     */
    private String addArticleWhereStr() {
        String whereStr = "";
        whereStr += addWhere("title", request.getParameter("articleTitle"));
        whereStr += addWhere("writer", request.getParameter("articleAuthor"));
        whereStr += addWhere("source", request.getParameter("articleFrom"));
        whereStr += addWhere("intro", request.getParameter("articleIntro"));

        String catagoryId = request.getParameter("catagoryId");
        String level = request.getParameter("level");
        if (StringUtil.isEmptyOrNull(catagoryId) || StringUtil.isEmptyOrNull(level)) return whereStr;
        if ("1".equals(level))
            whereStr += " AND catagory_one_id = " + catagoryId;
        else if ("2".equals(level))
            whereStr += " AND catagory_two_id = " + catagoryId;
        return whereStr;
    }

    /**
     *
     * @param a 数据库对应属性名
     * @param b 属性值
     * @return
     */
    private String addWhere(String a, String b) {
        if (!StringUtil.isEmptyOrNull(b)) {
            return " AND " + a + " LIKE '%" + b + "%'";
        }
        return "";
    }


    /**
     * 添加文章视图
     * @return 视图
     */
    @RequestMapping("/insert/index.do")
    public String articleInsertIndex() {
        return "/article/articleInsert";
    }

    /**
     * 添加文章
     * @return 添加结果
     */
    @RequestMapping("/insert.do")
    @ResponseBody
    public Object articleInsert(Article article) {
        article.setStatus(0);
        article.setOpenNum(0);
        return articleSaveOrUpdateHandel(true, article);
    }

    /**
     * 修改文章视图
     * @param id 预修改id
     * @return 视图
     */
    @RequestMapping("/update/index.do")
    public String articleUpdateIndex(Integer id) {
        try {
            Article article = baseService.get(Article.class, id);
            request.setAttribute("article", article);
            return "/article/articleUpdate";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新文章
     * @return 更新结果
     */
    @RequestMapping("/update.do")
    @ResponseBody
    public Object articleUpdate(Article article) {
        return articleSaveOrUpdateHandel(false, article);
    }

    /**
     * 删除文章
     * @return 删除结果
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object articleDelete(Article article) {
        JSONObject resp = new JSONObject();
        return handelDelete(article, resp);
    }

    /**
     * 处理文章的添加与修改
     * @param isSave true:添加
     * @param article 预处理对象
     * @return 处理结果
     */
    private Object articleSaveOrUpdateHandel(Boolean isSave, Article article) {
        Integer categoryOneId = article.getCatagoryOneId();
        Integer categoryTwoId = article.getCatagoryTwoId();
        if (categoryOneId != null) {
            article.setCatagoryOne(getCategaryName(categoryOneId));
        }
        if (categoryTwoId != null) {
            article.setCatagoryTwo(getCategaryName(categoryTwoId));
        }
        article.setUpdateTime(new Date());
        article.setThumbnailImg(ThumbnailatorUtils.imgUrlToThumbnaiUrl(article.getImg()));
        // 如果是添加
        if (isSave) {
            article.setCreateTime(new Date());
            return handleSave(article);
        }
        // 修改
        return handelArticleUpdate(article);
    }

    private String getCategaryName(Integer id) {
        try {
            ArticleCatagory articleCatagory = baseService.get(ArticleCatagory.class, id);
            return articleCatagory.getName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 处理文章更新
     * @param article 预处理对象
     * @return 处理结果
     */
    private Object handelArticleUpdate(Article article) {
        try {
            Article uda = baseService.get(Article.class, article.getId());
            if (article.getCatagoryTwoId() == null) {
                uda.setCatagoryTwoId(null);
                uda.setCatagoryTwo("");
            }
            return handleUpdate(article, uda);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resp = new JSONObject();
            resp.put("success", false);
            resp.put("msg", e.toString());
            return JSON.toJSON(resp);
        }
    }

    /**
     * 处理文章的禁用与启用
     * @param id ids
     * @param status
     * @return
     */
    @RequestMapping("/changeArticleStatusToEnableOrDisable.do")
    @ResponseBody
    public Object changeArticleStatusToEnableOrDisable(String id, Integer status) {
        JSONObject resp = new JSONObject();
        try {
            String sql;
            Date date = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = sf.format(date);
            if (status == 1) {
                sql = "UPDATE qy_article a " +
                        "SET a.`status` = '1', a.update_time = '"  + dateStr + "' " +
                        "WHERE a.`status`='0' " +
                        "AND a.id IN (" + id + ") " +
                        "AND EXISTS (SELECT ac.id FROM qy_article_catagory ac " +
                        "WHERE ((a.catagory_two_id = ac.id OR (a.catagory_two_id = " + null +" AND a.catagory_one_id = ac.id))) " +
                        "AND ac.`status`='1')";
            } else {
                sql = "UPDATE qy_article a " +
                        "SET a.`status` = '0', a.update_time = '" + dateStr + "' " +
                        "WHERE a.`status`='1' " +
                        "AND a.id IN (" + id + ") ";
            }
            baseService.excuteSQL(sql);
            resp.put("success", true);
        } catch (Exception e) {
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }


    /******************************  公共处理部分  *******************************/
    /**
     * 添加或修改时上级分类树数据查询
     * @return
     */
    @RequestMapping("/category/getArticleCategoryCombobox.do")
    @ResponseBody
    public Object getArticleCategoryCombobox() {
        try {
            String hql;
            String article = request.getParameter("article");
            if (StringUtil.isEmptyOrNull(article)) {
                hql = "from ArticleCatagory where level = 1 order by ord desc";
            } else {
                hql = "from ArticleCatagory order by ord desc";
            }
            List<ArticleCatagory> list = baseService.findByHql(hql);
            return buildArticleTree(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 构建树
     * @param articleCatagories
     * @return
     */
    private List<Tree> buildArticleTree(List<ArticleCatagory> articleCatagories) {
        try {
            List<Tree> trees = new ArrayList<Tree>();
            for (ArticleCatagory articleCatagory : articleCatagories) {
                Tree articTree = new Tree();
                articTree.setId(articleCatagory.getId());
                articTree.setPid(articleCatagory.getParentId());
                articTree.setText(articleCatagory.getName());
                trees.add(articTree);
            }
            return trees;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将保存单独提出来
     * @param newObject
     * @return
     */
    private Object handleSave(Object newObject) {
        JSONObject resp = new JSONObject();
        try {
            baseService.save(newObject);
            resp.put("success", true);
            resp.put("msg", "添加");
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }

    /**
     * 将修改单独提出来
     * @param newObject
     * @param oldObject
     * @return
     */
    private Object handleUpdate(Object newObject, Object oldObject) {
        JSONObject resp = new JSONObject();
        if (oldObject != null) {
            BeanUtil.copyProperties(newObject, oldObject);
            try {
                baseService.update(oldObject);
                resp.put("success", true);
                resp.put("msg", "修改");
            } catch (Exception e) {
                e.printStackTrace();
                resp.put("success", false);
                resp.put("msg", e.toString());
            }
        } else {
            resp.put("success", false);
            resp.put("msg", "修改失败");
        }
        return JSON.toJSON(resp);
    }

    private Object handelDelete(Object object, JSONObject resp) {
        try {
            resp.put("success", true);
            baseService.delete(object);
        } catch (Exception e) {
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }

    /**
     * 自动补全
     */
    @RequestMapping("/autoCompleteData.do")
    @ResponseBody
    public Object autoCompleteData() {
        List<AutoCompleteBean> list = new ArrayList<AutoCompleteBean>();
        try {
            String query = request.getParameter("query");
            query = StringUtil.iosToUTF8(query).trim();
            if("".equals(query)){return null;}
            System.out.println(query);
            if (StringUtil.isEmptyOrNull(query)) {
                return new AutoCompleteResponse(list);
            }
            String sql = "SELECT title as `value`,concat(id,'') AS `data` FROM qy_article WHERE status=1  and title LIKE '%"+ query +"%'";
            list = baseService.findBeanBySQL(sql,AutoCompleteBean.class,new HibernatePage(1,10));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AutoCompleteResponse(list);
    }
}
